package kr.ac.kongju.gedl.board.web;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import kr.ac.kongju.gedl.attach.service.AttachFileService;
import kr.ac.kongju.gedl.attach.vo.AttachFileVO;
import kr.ac.kongju.gedl.board.service.BoardContentsService;
import kr.ac.kongju.gedl.board.vo.BulletinBoardVO;
import kr.ac.kongju.gedl.board.vo.ContentsVO;
import kr.ac.kongju.gedl.cmmn.web.CU;
import kr.ac.kongju.gedl.code.vo.CodeInfoVO;
import kr.ac.kongju.gedl.common.util.ListResultVO;
import kr.ac.kongju.gedl.common.util.ResultCommand;

import org.apache.commons.lang.StringUtils;
import org.dozer.DozerBeanMapperSingletonWrapper;
import org.dozer.Mapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

@Controller
public class BoardContentsController {
	
	/** EgovPropertyService */
    @Resource(name = "propertiesService")
    protected EgovPropertyService propertiesService;
    
    @Resource(name = "reportService")
    protected BoardContentsService boardContentsService;
    
    
    @Resource(name = "attachFileService")
    protected AttachFileService attachFileService;
    
	
	@RequestMapping(value="/board/contentsList.do")
	public String selectReportList(@ModelAttribute("searchVO") ContentsVO searchVO, 
    		ModelMap model, SessionStatus status) throws Exception {
		
		searchVO.setRowPerPage(10);
		ListResultVO<ContentsVO> resultList = boardContentsService.retrieveListBoardContents(searchVO);
		
		//페이징을 구성한다
		PaginationInfo paginationInfo = new PaginationInfo();

		paginationInfo.setCurrentPageNo(searchVO.getPage());
		paginationInfo.setRecordCountPerPage(searchVO.getRowPerPage());
		paginationInfo.setPageSize(searchVO.getPageSize());
		
		paginationInfo.setTotalRecordCount(resultList.getListCount());
		
		BulletinBoardVO boardInfo = boardContentsService.retrieveBulletinBoard(searchVO.getBoardId());
		
		for(ContentsVO vo : resultList.getList()) {
			String desc = vo.getContentsDesc().replaceAll("\\<.*?\\>", "");
			vo.setContentsDesc(desc);
		}
		
		model.addAttribute("searchVO",searchVO);
		model.addAttribute("boardInfo", boardInfo);
		model.addAttribute("listResult", resultList);
		model.addAttribute("paginationInfo", paginationInfo);
		status.setComplete();
		
		return boardInfo.getBoardUrl();
	}
	
	@RequestMapping(value="/board/contentsView.do")
	public String selectReport(@ModelAttribute("searchVO") ContentsVO searchVO, 
    		ModelMap model, SessionStatus status) throws Exception {

		String returnUrl = "/board/contentsView";
		List<ContentsVO> contentsGroupList = new ArrayList<ContentsVO>();
		boardContentsService.updateViewCnt(searchVO);
		
		if(searchVO.getContentsGroupId() > 0){
			//조회수 갱신
			contentsGroupList = boardContentsService.retrieveBoardContents(searchVO);
			for(ContentsVO vo : contentsGroupList) {
				AttachFileVO searchCondition = new AttachFileVO();
				searchCondition.setContentsId(vo.getContentsGroupId()+"_"+vo.getContentsSeq());
				List<AttachFileVO> attachFileList = attachFileService.selectListAttachFile(searchCondition);
				vo.setAttachFileList(attachFileList);
			}
			
		} else {
			returnUrl = "forward:/board/contentsList.do";
		}
		   
		model.addAttribute("boardInfo", boardContentsService.retrieveBulletinBoard(searchVO.getBoardId()));
		model.addAttribute("searchVO",searchVO);
		model.addAttribute("contentsGroupList", contentsGroupList);
		
		status.setComplete();
		
		return returnUrl;
	}
	
	@RequestMapping(value="/board/mapViewer.do")
	public String selectMap(@ModelAttribute("attachFileVO") AttachFileVO searchVO,
    		ModelMap model) throws Exception {
		
		AttachFileVO attachFile = attachFileService.retrieveAttachFile(searchVO);
		
		model.addAttribute("attachFile",attachFile);
		
		
		return "/board/mapViewer";
	}
	
	
	@RequestMapping(value="/board/contentsForm.do")
	public String registrationReport(@ModelAttribute("contentsVO") ContentsVO contentsVO, 
    		ModelMap model, SessionStatus status) throws Exception {
		
		ContentsVO boardContentsVO = new ContentsVO();
		
		if(contentsVO.getContentsGroupId() > 0){
			List<ContentsVO> contentsGroupList = boardContentsService.retrieveBoardContents(contentsVO);
			if(contentsGroupList != null && contentsGroupList.size() == 1) {
				boardContentsVO = contentsGroupList.get(0);
			}
		} else {
			boardContentsVO.setBoardId(contentsVO.getBoardId());
		}
		
		model.addAttribute("boardInfo", boardContentsService.retrieveBulletinBoard(contentsVO.getBoardId()));
		model.addAttribute("contentsVO", boardContentsVO);
		
		status.setComplete();
		
		return "/board/contentsWrite";
	}
	
	@RequestMapping(value="/board/insertContents.do", method=RequestMethod.POST)
	public String insertReport(@ModelAttribute("contentsVO") ContentsVO contentsVO, 
    		ModelMap model, SessionStatus status) throws Exception {
		
		if(contentsVO.getContentsGroupId() == 0) {
			contentsVO.setContentsGroupId(boardContentsService.getContentsGroupId());
			contentsVO.setContentsSeq(1);
			contentsVO.setContentsDepth(1);
		} else {
			contentsVO.setContentsSeq(boardContentsService.getContentsSeq(contentsVO.getContentsGroupId()));
			contentsVO.setContentsDepth(contentsVO.getContentsDepth()+1);
		}
		
		boardContentsService.registerBoardContents(contentsVO);
		
		status.setComplete();
		
		return "redirect:/board/contentsView.do?boardId="+contentsVO.getBoardId()+"&contentsGroupId="+contentsVO.getContentsGroupId();
	}
	
	@RequestMapping(value="/board/updateContents.do", method=RequestMethod.POST)
	public String updateReport(@ModelAttribute("contentsVO") ContentsVO contentsVO, 
    		ModelMap model, SessionStatus status) throws Exception {
		
		ContentsVO boardContentsVO = new ContentsVO();
		
		if(contentsVO.getContentsGroupId() > 0 && contentsVO.getContentsSeq() > 0){
			boardContentsVO = boardContentsService.updateBoardContents(contentsVO);
		}
		
		status.setComplete();
		
		return "redirect:/board/contentsView.do?boardId="+boardContentsVO.getBoardId()+"&contentsGroupId="+boardContentsVO.getContentsGroupId();
	}
	
	@RequestMapping(value="/board/deleteContents.do", method=RequestMethod.POST)
	public ModelAndView deleteReport(@ModelAttribute("contentsVO") ContentsVO contentsVO, 
    		ModelMap model, SessionStatus status) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView("jsonView");
		
		if(contentsVO.getContentsGroupId() > 0){	//등록
			int result = boardContentsService.deleteBoardContents(contentsVO);
			if(result > 0){
				modelAndView.addObject(ResultCommand.RESULT, "true");
	            modelAndView.addObject(ResultCommand.MESSAGE, "삭제되었습니다.");
	            
	            //첨부파일 정보를 삭제한다
	            //int deleteRowCount = attachFileMgr.deleteListAttachFile("NOTICE", boardContents.getBoardContentsId());
	            //logger.info("[DELETE] targetId:{} attachFile count:{}", boardContents.getBoardContentsId(), deleteRowCount);
	            
	            //기존 첨부파일 사용안함으로 플래그 처리
				AttachFileVO attachFile = new AttachFileVO();
				int updateResult = attachFileService.updateListAttachFile(attachFile);
				//logger.info("[DEBUG] updateListAttachFile result:{}", updateResult);
			}else{
				modelAndView.addObject(ResultCommand.RESULT, "false");
	            modelAndView.addObject(ResultCommand.MESSAGE, "삭제시 오류가 발생하였습니다");
			}
		}else{											//갱신
			modelAndView.addObject(ResultCommand.RESULT, "false");
            modelAndView.addObject(ResultCommand.MESSAGE, "삭제시 오류가 발생하였습니다");
		}
		
		status.setComplete();
		
		return modelAndView;
	}
	
	
	/**
	 * 컨텐츠 비밀번호 검사
	 * @param contentsVO
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/board/popup.do")
	public String popup(@ModelAttribute("contentsVO") ContentsVO contentsVO, 
    		SessionStatus status) throws Exception {
		
		
		return "/board/popup";
	}
	
	
	
	/**
	 * 컨텐츠 비밀번호 검사
	 * @param contentsVO
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/board/checkPassword.do", method=RequestMethod.POST)
	public ModelAndView confirmPassword(@ModelAttribute("contentsVO") ContentsVO contentsVO, 
    		SessionStatus status) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView("jsonView");
		
		try{
			if(!StringUtils.isEmpty(contentsVO.getPassword()) 
					&& contentsVO.getContentsGroupId() > 0){	//등록	
				String password = contentsVO.getPassword();
				ContentsVO boardContents = new ContentsVO();
				List<ContentsVO> contentsGroupList = boardContentsService.retrieveBoardContents(contentsVO);
				if(contentsGroupList != null && contentsGroupList.size() == 1) {
					boardContents = contentsGroupList.get(0);
				}
				if(password.trim().equals(boardContents.getPassword())){
					modelAndView.addObject(ResultCommand.RESULT, "true");
					modelAndView.addObject(ResultCommand.MESSAGE, "비밀번호 일치");
				}else{
					modelAndView.addObject(ResultCommand.RESULT, "false");
					modelAndView.addObject(ResultCommand.MESSAGE, "비밀번호가 일치하지 않습니다.");
				}
			}else{
				modelAndView.addObject(ResultCommand.RESULT, "false");
				modelAndView.addObject(ResultCommand.MESSAGE, "비밀번호가 올바르지 않습니다");
			}
		}catch (Exception e){
			
			modelAndView.addObject(ResultCommand.RESULT, "false");
			modelAndView.addObject(ResultCommand.MESSAGE, "비밀번호시 오류가 발생하였습니다" + e.toString());
		}
		
		status.setComplete();
		
		return modelAndView;
	}
	
	
}
